/**
 * 网络请求拦截器 - 后台脚本
 * 负责拦截网络请求并实现Mock功能
 */


/*@desc
*  查找
* */
function utilFindOne(aray, cb) {
  for (let i = 0; i < aray?.length; i++) {
    var isexit = cb(aray[i], i)
    if (isexit) {
      return aray[i]
    }
  }

}

class NetworkInterceptorBackground {
  constructor() {
    this.isEnabled = true;
    this.webList = [];
    this.mockList = [];
    this.requestList = [];
    this.requestRules = new Map();
    // 是否每次请求都把request 存起来
    this.enanbleStorgeLogRequest = false

    this.init();
  }

  /**
   * 初始化后台脚本
   */
  async init() {
    await this.loadData();
    this.setupRequestInterception();
    this.setupMessageListener();
    this.setupStorageListener();

    // 清除所有现有的右键菜单，避免重复创建
    chrome.contextMenus.removeAll(() => {
      // 创建主菜单 - AI工具
      chrome.contextMenus.create({
        id: "aiToolsMenu",
        title: "AI工具",
        contexts: ["page", "selection"]
      });

      // 创建子菜单 - 问AI菜单（仅在选中文本时显示）
      chrome.contextMenus.create({
        id: "askAiSubMenu",
        parentId: "aiToolsMenu",
        title: "问AI菜单",
        contexts: ["page", "selection"]
      });

      // 创建子菜单 - AI总结文章（在页面和选中文本时都显示）
      chrome.contextMenus.create({
        id: "aiSummarySubMenu",
        parentId: "aiToolsMenu",
        title: "ai总结文章",
        contexts: ["page", "selection"]
      });
    });

    // 监听菜单点击事件
    chrome.contextMenus.onClicked.addListener((info, tab) => {
      if (info.menuItemId === "askAiSubMenu" && info.selectionText) {
        // 存储选中的文本
        chrome.storage.local.set({ selectedText: info.selectionText }, () => {
          // 打开弹出框
          chrome.windows.create({
            url: chrome.runtime.getURL("popup.html"),
            type: "popup",
            width: 900,
            height: 500
          });
        });
      }

      if (info.menuItemId === "aiSummarySubMenu") {
        // 存储选中的文本
          chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
              const currentUrl = tabs?.[0]?.url;
              console.log('当前页面URL:', currentUrl);

              chrome.storage.local.set({ currentUrl: currentUrl }, () => {
                  // 打开AI总结文章弹出框
                  chrome.windows.create({
                      url: chrome.runtime.getURL("popup_summary.html"),
                      type: "popup",
                      width: 900,
                      height: 500
                  });
              });
          });

      }
    });

    console.log('[init function ]： NetworkInterceptorBackground 网络请求拦截器已启动');
  }

  /**
   * 从存储中加载数据
   */
  async loadData() {
    try {
      const result = await chrome.storage.local.get([
        'whitelist', 'mockList', 'requestList', 'isEnabled'
      ]);

      this.webList = result.whitelist || [];
      this.mockList = result.mockList || [];
      this.requestList = result.requestList || [];
      this.isEnabled = result.isEnabled !== false;

      console.log('数据加载完成:', {
        webList: this.webList.length,
        mockList: this.mockList.length,
        requestList: this.requestList.length,
        isEnabled: this.isEnabled
      });
    } catch (error) {
      console.error('加载数据失败:', error);
    }
  }

  /**
   * 保存数据到存储
   */
  async saveData() {
    try {
      await chrome.storage.local.set({
        webList: this.webList,
        mockList: this.mockList,
        requestList: this.requestList,
        isEnabled: this.isEnabled
      });
    } catch (error) {
      console.error('保存数据失败:', error);
    }
  }

  /**
   * 设置网络请求拦截
   */
  setupRequestInterception() {
    // 监听请求开始
    chrome.webRequest.onBeforeRequest.addListener(
      (details) => this.handleBeforeRequest(details),
      { urls: ['<all_urls>'] },
      ['requestBody']
    );

    // 监听请求头
    chrome.webRequest.onBeforeSendHeaders.addListener(
      (details) => this.handleBeforeSendHeaders(details),
      { urls: ['<all_urls>'] },
      ['requestHeaders']
    );

    // 监听响应头
    chrome.webRequest.onHeadersReceived.addListener(
      (details) => this.handleHeadersReceived(details),
      { urls: ['<all_urls>'] },
      ['responseHeaders']
    );

    // 监听请求完成
    chrome.webRequest.onCompleted.addListener(
      (details) => this.handleRequestCompleted(details),
      { urls: ['<all_urls>'] },
      ['responseHeaders']
    );

    // 监听请求错误
    /*    chrome.webRequest.onErrorOccurred.addListener(
          (details) => this.handleRequestError(details),
          { urls: ['<all_urls>'] }
        );*/
  }

  /**
   * 处理请求开始事件
   */
  handleBeforeRequest(details) {
    if (!this.isEnabled || !this.shouldInterceptUrl(details.url)) {
      return;
    }

    /* // 检查是否有匹配的Mock规则
     const mockRule = this.findMatchingMockRule(details.url);
     console.log("🚀 ~  mockJson:",details.url, mockRule)
     if (mockRule && !mockRule.disabled) {
       // 创建Mock响应
       const mockResponse = this.createMockResponse(mockRule, details);

       // 记录请求信息
       this.recordRequest(details, mockResponse.statusCode, JSON.stringify(mockRule.mockJson), true);

       // 返回重定向到data URL来模拟响应
       return {
         redirectUrl: this.createDataUrl(mockRule.mockJson, mockResponse.statusCode)
       };
     }*/

    // 记录请求信息
    this.recordRequestStart(details);
  }

  /**
   * 处理请求头事件
   */
  handleBeforeSendHeaders(details) {
    if (!this.isEnabled || !this.shouldInterceptUrl(details.url)) {
      return;
    }

    // 更新请求信息
    this.updateRequestHeaders(details);
  }

  /**
   * 处理响应头事件
   */
  handleHeadersReceived(details) {
    if (!this.isEnabled || !this.shouldInterceptUrl(details.url)) {
      return;
    }

    // 检查是否有匹配的Mock规则
    const mockRule = this.findMatchingMockRule(details.url);
    if (mockRule && mockRule.enabled) {
      // 修改响应头
      const headers = details.responseHeaders || [];

      // 设置CORS头
      headers.push(
        { name: 'Access-Control-Allow-Origin', value: '*' },
        { name: 'Access-Control-Allow-Methods', value: 'GET, POST, PUT, DELETE, OPTIONS' },
        { name: 'Access-Control-Allow-Headers', value: '*' }
      );

      return { responseHeaders: headers };
    }
  }

  /**
   * 处理请求完成事件
   */
  handleRequestCompleted(details) {
    if (!this.isEnabled || !this.shouldInterceptUrl(details.url)) {
      return;
    }

    // 更新请求完成信息
    this.updateRequestCompleted(details);
  }

  /**
   * 处理请求错误事件
   */
  handleRequestError(details) {
    if (!this.isEnabled || !this.shouldInterceptUrl(details.url)) {
      return;
    }

    // 记录请求错误
    this.updateRequestError(details);
  }

  /**
   * 判断是否应该拦截URL
   */
  shouldInterceptUrl(url) {
    if (this.webList.length === 0) {
      return false;
    }
    return this.webList.some(domain => {
      return url?.indexOf(domain) >= 0
    });
  }

  /**
   * 查找匹配的Mock规则
   */
  findMatchingMockRule(url/**请求进来的url */, method = null) {
    var exitone = utilFindOne(this.mockList, _mock => (_mock?.url)?.indexOf(url) >= 0)
    if (!exitone/*沒有找到這個url的拦截数据*/) {
      return false
    }
    if (!exitone?.enabled/*找到了，但是不开启*/) {
      return false
    }
    return exitone
  }

  /**
   * 创建Mock响应
   */
  createMockResponse(mockRule, details) {
    const response = {
      statusCode: mockRule.statusCode || 200,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: mockRule.mockJson
    };

    // 如果设置了延迟，添加延迟处理
    if (mockRule.delay > 0) {
      setTimeout(() => {
        // 延迟处理逻辑
      }, mockRule.delay);
    }

    return response;
  }

  /**
   * 创建Data URL用于Mock响应
   */
  createDataUrl(data, statusCode = 200) {
    const jsonString = JSON.stringify(data);
    const base64Data = btoa(unescape(encodeURIComponent(jsonString)));
    return `data:application/json;base64,${base64Data}`;
  }

  /**
   * 记录请求开始
   */
  recordRequestStart(details) {
    const requestInfo = {
      id: this.generateId(),
      method: details.method,
      url: details.url,
      requestBody: this.extractRequestBody(details),
      requestParams: this.extractRequestParams(details.url),
      requestHeaders: {},
      responseCode: 0,
      responseBody: '',
      timestamp: Date.now(),
      timeDesc: new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '年').replace(/,/g, '').replace(/:/g, '时'),
      isMocked: false,
      tabId: details.tabId,
      frameId: details.frameId
    };

    this.requestRules.set(details.requestId, requestInfo);
  }

  /**
   * 更新请求头信息
   */
  updateRequestHeaders(details) {
    const requestInfo = this.requestRules.get(details.requestId);
    if (requestInfo) {
      requestInfo.requestHeaders = this.headersToObject(details.requestHeaders/*设置 request header进去  requestRules */);
    }
  }

  /**
   * 更新请求完成信息
   */
  updateRequestCompleted(details) {
    const requestInfo = this.requestRules.get(details.requestId);
    if (requestInfo) {
      requestInfo.responseCode = details.statusCode;


      // 添加到请求列表
      this.addToRequestList(requestInfo);

      // 清理临时存储
      this.requestRules.delete(details.requestId);
    }
  }

  /**
   * 更新请求错误信息
   */
  updateRequestError(details) {
    const requestInfo = this.requestRules.get(details.requestId);
    if (requestInfo) {
      requestInfo.responseCode = 0;
      requestInfo.responseBody = `Error: ${details.error}`;

      // 添加到请求列表
      this.addToRequestList(requestInfo);

      // 清理临时存储
      this.requestRules.delete(details.requestId);
    }
  }

  /**
   * 记录请求信息（用于Mock请求）
   */
  recordRequest(details, statusCode, responseBody, isMocked = false) {
    const requestInfo = {
      id: this.generateId(),
      method: details.method,
      url: details.url,
      requestBody: this.extractRequestBody(details),
      requestParams: this.extractRequestParams(details.url),
      requestHeaders: {},
      responseCode: statusCode,
      responseBody: responseBody,
      timestamp: Date.now(),
      isMocked: isMocked,
      tabId: details.tabId,
      frameId: details.frameId
    };

    this.addToRequestList(requestInfo);
  }

  /**
   * 查找现有请求（URL幂等匹配）
   * @param {string} url - 请求URL
   * @param {number} timestamp - 请求时间戳
   * @param {number} timeWindow - 时间窗口（毫秒，默认5秒）
   * @returns {object|null} 匹配的请求对象或null
   */
  findExistingRequest(url, timestamp, timeWindow = 5000) {
    return this.requestList.find(request => {
      const timeDiff = Math.abs(request.timestamp - timestamp);
      return request.url === url && timeDiff <= timeWindow;
    });
  }

  /**
   * 更新现有请求的响应体信息
   * @param {object} existingRequest - 现有请求对象
   * @param {object} newRequestInfo - 新的请求信息
   */
  async updateExistingRequest(existingRequest, newRequestInfo) {
    // 更新响应体相关信息
    existingRequest.responseCode = newRequestInfo.responseCode || existingRequest.responseCode;
    existingRequest.responseBody = newRequestInfo.responseBody || existingRequest.responseBody;

    // 如果新请求有更完整的信息，则更新
    if (newRequestInfo.requestHeaders && Object.keys(newRequestInfo.requestHeaders).length > 0) {
      existingRequest.requestHeaders = { ...existingRequest.requestHeaders, ...newRequestInfo.requestHeaders };
    }

    await this.saveData();

    // 通知弹窗更新
    this.notifyPopup('REQUEST_UPDATED', { request: existingRequest });
  }

  /**
   * 添加到请求列表
   */
  async addToRequestList(requestInfo) {
    // 限制请求列表大小，避免内存溢出
    if (this.requestList.length >= 100) {
      this.requestList = this.requestList.slice(0, 50);
    }

    this.requestList.unshift(requestInfo);
    await this.saveData();

    // 通知弹窗更新
    // this.notifyPopup('NEW_REQUEST', { request: requestInfo });
  }

  /**
   * 提取请求体
   */
  extractRequestBody(details) {
    if (!details.requestBody) return '';

    try {
      if (details.requestBody.formData) {
        return JSON.stringify(details.requestBody.formData);
      } else if (details.requestBody.raw) {
        const decoder = new TextDecoder();
        return details.requestBody.raw.map(data =>
          decoder.decode(data.bytes)
        ).join('');
      }
    } catch (error) {
      console.error('提取请求体失败:', error);
    }

    return '';
  }

  /**
   * 提取请求参数
   */
  extractRequestParams(url) {
    try {
      const urlObj = new URL(url);
      return urlObj.search;
    } catch (error) {
      return '';
    }
  }

  /**
   * 将请求头数组转换为对象
   */
  headersToObject(headers) {
    const result = {};
    if (headers) {
      headers.forEach(header => {
        result[header.name] = header.value;
      });
    }
    return result;
  }

  /**
   * 尝试获取响应体
   * @param {object} details - 请求详情
   * @param {object} requestInfo - 请求信息对象
   * @returns {Promise<string|null>} 响应体内容
   */
  async tryGetResponseBody(details, requestInfo) {


    // 如果没有启用debugger模式，返回null
    return null;
  }

  /**
   * 设置消息监听器
   */
  setupMessageListener() {
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      this.handleMessage(message, sender, sendResponse);
      return true; // 保持消息通道开放
    });
  }

  /**
   * 处理来自弹窗和content script的消息
   */
  async handleMessage(message, sender, sendResponse) {
    switch (message.type) {
      case 'TOGGLE_PLUGIN':
        this.isEnabled = message.enabled;
        await this.saveData();
        sendResponse({ success: true });
        break;

      case 'GET_DATA':
        sendResponse({
          webList: this.webList,
          mockList: this.mockList,
          requestList: this.requestList,
          isEnabled: this.isEnabled
        });
        break;

      case 'UPDATE_DATA':
        if (message.data) {
          Object.assign(this, message.data);
          await this.saveData();
        }
        sendResponse({ success: true });
        break;

      case 'RECORD_REQUEST':
        // 处理来自content script的请求记录
        if (message.data?.request) {
          const requestInfo = message.data?.request;
          if (!this.enanbleStorgeLogRequest) {
            // console.log('如果没有开启 就是不需要记录每一次的网络请求  调试的时候可以开启，')
            return
          }

          // 尝试查找现有请求（URL幂等匹配）
          const existingRequest = this.findExistingRequest(requestInfo.url, requestInfo.timestamp);

          if (existingRequest) {
            // 更新现有请求的响应体信息
            await this.updateExistingRequest(existingRequest, requestInfo);
            sendResponse({ success: true, updated: true, requestId: existingRequest.id });
          } else {
            // 创建新请求记录
            await this.addToRequestList(requestInfo);
            sendResponse({ success: true, updated: false, requestId: requestInfo.id });
          }
        } else {
          sendResponse({ error: 'Missing requestInfo' });
        }
        break;

      case 'SHOULD_INTERCEPT':
        // 检查是否应该拦截请求
        const shouldIntercept = this.isEnabled && this.shouldInterceptUrl(message.data?.url);
        sendResponse({ shouldIntercept: shouldIntercept });
        break;

      case 'CHECK_MOCK_RULES':
        // 检查Mock规则
        const mockRule = this.findMatchingMockRule(message.data?.url, message.data?.method);
        /*  console.log('background.js find mockRule',
              `URL：${message.data?.url}，
              mocklist :${this.mockList?.map(i2=>i2?.url)}
              mockRule:${mockRule}`
              );*/
        // 没有开启 模拟
        if (mockRule?.enabled) {
          sendResponse({ mockRule: mockRule });
        } else {
          sendResponse();
        }

        break;


      case 'SETTINGS_UPDATED':
        console.log('watch：配置修改 大部分来之 options的修改')
        /*
           console.log(`
           message, sender, sendResponse
           ${JSON?.stringify(message)},
               ${JSON.stringify((sender))},
           `)*/
        await this.loadData();
        sendResponse();
        break;
      default:
        sendResponse({ error: 'Unknown message type' });
    }
  }

  /**
   * 设置存储监听器  对chrome storage的watch
   */
  setupStorageListener() {
    chrome.storage.onChanged.addListener((changes, namespace) => {
      if (namespace === 'local') {
        this.handleStorageChange(changes);

      }
    });
  }

  /**
   * 处理存储变化
   */
  handleStorageChange(changes) {
    if (changes.webList) {
      this.webList = changes.webList.newValue || [];
    }
    if (changes.mockList) {
      this.mockList = changes.mockList.newValue || [];
    }
    if (changes.requestList) {
      this.requestList = changes.requestList.newValue || [];
    }
    if (changes.isEnabled) {
      this.isEnabled = changes.isEnabled.newValue !== false;
    }
    if (changes.enanbleStorgeLogRequest) {
      this.enanbleStorgeLogRequest = changes.enanbleStorgeLogRequest.newValue
    }


    console.log('watch Storage change');
  }

  /**
   * 通知弹窗
   */
  notifyPopup(type, data) {
    chrome.runtime.sendMessage({
      type: type,
      ...data
    }).catch(() => {
      // 弹窗可能未打开，忽略错误
    });
  }

  /**
   * 生成唯一ID
   */
  generateId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
  }
}

// 初始化后台脚本
const backgroundScript = new NetworkInterceptorBackground();

/**
 * Debugger管理器类
 * 负责使用Chrome DevTools Protocol获取网络响应体
 */
/*class DebuggerManager {
  constructor() {
    this.attachedTabs = new Set();
    this.pendingRequests = new Map(); // 存储待处理的请求
    this.setupEventListeners();
  }

  /!**
   * 附加debugger到指定标签页
   * @param {number} tabId - 标签页ID
   *!/
  async attachToTab(tabId) {
    try {
      // 检查是否已经附加
      if (this.attachedTabs.has(tabId)) {
        console.log(`Debugger已附加到标签页 ${tabId}`);
        return true;
      }

      await new Promise((resolve, reject) => {
        chrome.debugger.attach({ tabId: tabId }, "1.0", () => {
          if (chrome.runtime.lastError) {
            reject(chrome.runtime.lastError);
          } else {
            resolve();
          }
        });
      });

      // 启用Network域
      await this.sendCommand(tabId, "Network.enable", {});
      this.attachedTabs.add(tabId);
      console.log(`Debugger已成功附加到标签页 ${tabId}`);
      return true;
    } catch (error) {
      console.error(`附加debugger到标签页 ${tabId} 失败:`, error);
      return false;
    }
  }

  /!**
   * 从标签页分离debugger
   * @param {number} tabId - 标签页ID
   *!/
  async detachFromTab(tabId) {
    try {
      if (!this.attachedTabs.has(tabId)) {
        console.log(`标签页 ${tabId} 未附加debugger`);
        return;
      }

      await new Promise((resolve) => {
        chrome.debugger.detach({ tabId: tabId }, () => {
          resolve();
        });
      });

      this.attachedTabs.delete(tabId);
      // 清理该标签页的待处理请求
      for (let [key, value] of this.pendingRequests.entries()) {
        if (value.tabId === tabId) {
          this.pendingRequests.delete(key);
        }
      }
      console.log(`Debugger已从标签页 ${tabId} 分离`);
    } catch (error) {
      console.error(`从标签页 ${tabId} 分离debugger失败:`, error);
    }
  }

  /!**
   * 检查标签页是否已附加debugger
   * @param {number} tabId - 标签页ID
   * @returns {boolean}
   *!/
  isTabAttached(tabId) {
    return this.attachedTabs.has(tabId);
  }

  /!**
   * 发送debugger命令
   * @param {number} tabId - 标签页ID
   * @param {string} method - 命令方法
   * @param {object} params - 命令参数
   *!/
  sendCommand(tabId, method, params) {
    return new Promise((resolve, reject) => {
      chrome.debugger.sendCommand({ tabId: tabId }, method, params, (response) => {
        if (chrome.runtime.lastError) {
          reject(chrome.runtime.lastError);
        } else {
          resolve(response);
        }
      });
    });
  }

  /!**
   * 设置事件监听器
   *!/
  setupEventListeners() {
    // 监听debugger事件
    chrome.debugger.onEvent.addListener((source, method, params) => {
      if (method === "Network.responseReceived") {
        this.handleResponseReceived(source.tabId, params);
      } else if (method === "Network.loadingFinished") {
        this.handleLoadingFinished(source.tabId, params);
      }
    });

    // 监听debugger分离事件
    chrome.debugger.onDetach.addListener((source, reason) => {
      console.log(`Debugger从标签页 ${source.tabId} 分离，原因: ${reason}`);
      this.attachedTabs.delete(source.tabId);
    });

    // 监听标签页关闭事件
    chrome.tabs.onRemoved.addListener((tabId) => {
      if (this.attachedTabs.has(tabId)) {
        this.detachFromTab(tabId);
      }
    });

    // 监听标签页更新事件
    chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
      if (changeInfo.status === 'loading' && this.attachedTabs.has(tabId)) {
        // 页面重新加载时重新启用Network域
        this.sendCommand(tabId, "Network.enable", {}).catch(console.error);
      }
    });
  }

  /!**
   * 处理响应接收事件
   * @param {number} tabId - 标签页ID
   * @param {object} params - 事件参数
   *!/
  async handleResponseReceived(tabId, params) {
    try {
      const { requestId, response } = params;

      // 存储响应信息，等待加载完成
      this.pendingRequests.set(requestId, {
        tabId: tabId,
        response: response,
        timestamp: Date.now()
      });

      console.log(`响应接收: ${response.url} (${response.status})`);
    } catch (error) {
      console.error('处理响应接收事件失败:', error);
    }
  }

  /!**
   * 处理加载完成事件
   * @param {number} tabId - 标签页ID
   * @param {object} params - 事件参数
   *!/
  async handleLoadingFinished(tabId, params) {
    try {
      const { requestId } = params;
      const pendingRequest = this.pendingRequests.get(requestId);

      if (!pendingRequest) {
        return;
      }

      // 获取响应体
      const responseBody = await this.sendCommand(tabId, "Network.getResponseBody", {
        requestId: requestId
      });

      // 处理响应数据
      const responseData = {
        url: pendingRequest.response.url,
        status: pendingRequest.response.status,
        statusText: pendingRequest.response.statusText,
        headers: pendingRequest.response.headers,
        mimeType: pendingRequest.response.mimeType,
        body: responseBody.body,
        base64Encoded: responseBody.base64Encoded,
        timestamp: pendingRequest.timestamp
      };

      // 通知主系统
      this.notifyResponseCaptured(tabId, responseData);

      // 清理待处理请求
      this.pendingRequests.delete(requestId);

      console.log(`响应体已获取: ${responseData.url}`);
    } catch (error) {
      console.error('获取响应体失败:', error);
      // 清理失败的请求
      this.pendingRequests.delete(params.requestId);
    }
  }

  /!**
   * 通知响应已捕获
   * @param {number} tabId - 标签页ID
   * @param {object} responseData - 响应数据
   *!/
  notifyResponseCaptured(tabId, responseData) {
    // 更新现有的请求记录
    if (backgroundScript) {
      const existingRequest = backgroundScript.requestList.find(req =>
        req.url === responseData.url &&
        Math.abs(req.timestamp - responseData.timestamp) < 5000 // 5秒内的请求
      );

      if (existingRequest) {
        // 解码响应体
        let decodedBody = responseData.body;
        if (responseData.base64Encoded) {
          try {
            decodedBody = atob(responseData.body);
          } catch (e) {
            console.warn('Base64解码失败:', e);
          }
        }

        existingRequest.responseBody = decodedBody;
        existingRequest.responseHeaders = responseData.headers;

        // 保存更新的数据
        backgroundScript.saveData();

        // 通知popup更新
        backgroundScript.notifyPopup('RESPONSE_BODY_UPDATED', {
          requestId: existingRequest.id,
          responseBody: decodedBody
        });
      }
    }

    // 发送消息给其他组件
    chrome.runtime.sendMessage({
      type: 'RESPONSE_CAPTURED',
      tabId: tabId,
      data: responseData
    }).catch(() => {
      // 忽略发送失败的错误
    });
  }

  /!**
   * 获取所有附加的标签页
   * @returns {Set<number>}
   *!/
  getAttachedTabs() {
    return new Set(this.attachedTabs);
  }

  /!**
   * 清理过期的待处理请求
   *!/
  cleanupPendingRequests() {
    const now = Date.now();
    const timeout = 30000; // 30秒超时

    for (let [requestId, request] of this.pendingRequests.entries()) {
      if (now - request.timestamp > timeout) {
        this.pendingRequests.delete(requestId);
      }
    }
  }
}*/


/*
// 初始化debugger管理器
const debuggerManager = new DebuggerManager();

// 扩展消息处理以支持debugger功能 (暂时废弃)
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'START_DEBUGGING') {
    debuggerManager.attachToTab(message.tabId)
      .then(success => sendResponse({ success: success }));
    return true;
  } else if (message.action === 'STOP_DEBUGGING') {
    debuggerManager.detachFromTab(message.tabId)
      .then(() => sendResponse({ success: true }));
    return true;
  } else if (message.action === 'GET_DEBUGGER_STATUS') {
    sendResponse({
      attachedTabs: Array.from(debuggerManager.getAttachedTabs()),
      pendingRequests: debuggerManager.pendingRequests.size
    });
  }
});
*/

// 处理插件安装事件
chrome.runtime.onInstalled.addListener((details) => {
  console.log('onInstalled:网络请求拦截器已安装:', details.reason);
});

// 处理插件启动事件
chrome.runtime.onStartup.addListener(() => {
  console.log('onStartup:网络请求拦截器已启动');
});